package org.example;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MessageProducer implements CommandLineRunner {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void run(String... args) throws Exception {
        log.info("1111");
//        SendResult result = rocketMQTemplate.syncSend("test-topic", "1111");
//        log.info(JSONObject.toJSONString(result));
        log.info("2222");
    }

    /** 异步发送消息 */
    public void sendAsyncMessage(String messageBody) {
        rocketMQTemplate.asyncSend("test-topic", messageBody, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("异步消息发送成功: " + sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable e) {
                System.err.println("异步消息发送失败: " + e.getMessage());
            }
        });
    }
}
